/*
 * NotSoNaive.cpp
 *
 *  Created on: 12-08-2013
 *      Author: Krzychu
 */

#include "NotSoNaive.h"

#include "../Structures/Config.h"

#include <stdio.h>
#include <string.h>

NotSoNaive::NotSoNaive()
{

}

NotSoNaive::~NotSoNaive()
{

}

std::string NotSoNaive::getName()
{
	return "Not So Naive Search";
}

searchResult NotSoNaive::execute(std::string text, std::string pattern)
{
	searchResult result;
	result.iterationsTaken = 0;

	int textSize = text.size();
	int patternSize = pattern.size();

	int j, k, ell;

	/* Preprocessing */
	if (pattern[0] == pattern[1])
	{
		k = 2;
		ell = 1;
	}
	else
	{
		k = 1;
		ell = 2;
	}

	/* Searching */
	j = 0;
	while (j <= textSize - patternSize)
	{
		result.iterationsTaken++;

		if (pattern[1] != text[j + 1])
		{
			j += k;
		}
		else
		{
			if (memcmp(pattern.c_str() + 2, text.c_str() + j + 2, patternSize - 2) == 0 && pattern[0] == text[j])
			{
				result.positionsFound.push_back(j);
				if (Config::getInstance()->getFindOneOccurence())
				{
					return result;
				}
			}
			j += ell;
		}
	}

	return result;
}
